// ---------------------------------------------------------------------
//
// -- 项目Util
// -- author £
//
// ---------------------------------------------------------------------

const DEFAULT_SURL = 'https://onimg.leshu.com/wxgame/shareqr/cm_tanyitan_201806261420.jpg',
    DEFAULT_SICON = 'https://onimg.leshu.com/wxgame/shareqr/icon_tanyitan_201807041054.png';

// let SHARE_IMAGE_URL = 'https://onimg.leshu.com/wxgame/countcash/shareimg.png';

const G_W = 6,
    TEST_W = 5000,
    TRY_CODE_MAX_TIME = 300;

let _sItr = 0,
    _cW, _cH, _gridS, _gridH,
    _pW, _pScale,
    _code, _finish, _cStep, _tryCodeTime = 0,
    _codeStartTime, _codeEndTime,
    _scaleOnce = false;

let WGUtil = {
    wgUrls: null,
    wgIcons: null,
    /*getCode: function () {
        // return;
        let ps = new Uint8Array(new ArrayBuffer(TEST_W * 4)),
            index, i, cScale;
        console.log(ps);
        gl.readPixels(0, 0, TEST_W, 1, 6408, 5121, ps);

        for (i = 0; i < TEST_W; ++i) {
            index = 4 * i;

            if (ps[index] === 0 && ps[index + 1] === 0 &&
                ps[index + 2] === 0 && ps[index + 3] === 0) {
                break;
            }
        }

        _cW = require('UIManager').getRealW();
        _cH = require('UIManager').getRealH();
        _pW = i;
        _pScale = _cW / _pW;
        // cScale = Math.ceil(require('UIManager').getScaleW());
        cScale = Math.ceil(_pScale);
        _code = '';
        _tryCodeTime = 0;
        _gridS = cScale * G_W;

        console.log('P DATA========================');
        console.log(_pW);
        console.log(_pScale, cScale);
        console.log(_cW, _gridS);
        console.log('P DATA========================');
        _codeStartTime = new Date().getTime();

        _finish = false;
        _cStep = -1;

        // if (_gridS % 2 === 1) ++_gridS;

        wx.postMessage({
            message: 'code',
            cW: _cW,
            cH: _cH,
            gridS: _gridS,
            // gridH: (cScale % 2) === 1 ? (1 + cScale) :
            //     cScale
            gridH: _gridS,
        });
    },

    codeFail: function () {
        _code = '';
        console.log('codeFail');

        wx.postMessage({
            message: 'finish_code'
        });
    },

    parseCode: function () {
        if (_finish) return;

        let ps = new Uint8Array(new ArrayBuffer(_pW * 1 * 4));

        gl.readPixels(0, 0, _pW, 1, 6408, 5121, ps);

        let lastIndex = Math.floor(_cW / _gridS),
            lastHex = this.arr2Color(ps, lastIndex), curCode;

        if (lastHex !== '#000000' && !this.testaaa) {
            console.log('firstttttttttttttttttttttt');
            console.log(lastIndex, lastHex);
            console.log(ps);
            this.testaaa = true;
        }

        if (lastHex !== '#ffffff' && lastHex !== '#000000') {
            if (_code === '') {
                if (++_tryCodeTime === TRY_CODE_MAX_TIME) {
                    console.log('parse error3');
                    console.log(ps);
                    this.codeFail();
                    return true;
                }
            }

            return;
        }

        if (lastHex === '#000000') _finish = true;

        let tmpCode = '', flag = -1, stepIndex;

        for (let i = 1; i <= (lastIndex - 1); ++i) {
            curCode = parseInt(this.arr2Color(ps, i).replace('#', '0x'));
            // console.log('curCode:', curCode);
            // _code += String.fromCharCode(curCode);
            tmpCode += String.fromCharCode(curCode);
        }

        _finish = tmpCode.indexOf('cstepf') >= 0;
        stepIndex = tmpCode.indexOf('cstep');

        if (stepIndex < 0) {
            if (_code === '') {
                if (++_tryCodeTime === TRY_CODE_MAX_TIME) {
                    console.log('parse error0');
                    this.codeFail();
                    return true;
                }
            } else {
                console.log('parse error1');
                this.codeFail();
                return
            }
        }

        if (!_finish) {
            flag = parseInt(tmpCode.substring(stepIndex + 5));

            if (!flag && flag !== 0) {
                if (_code === '') {
                    if (++_tryCodeTime === TRY_CODE_MAX_TIME) {
                        console.log('parse error4');
                        console.log(ps);
                        this.codeFail();
                        return true;
                    }
                } else {
                    console.log('parse error2');
                    this.codeFail();
                    return true;
                }
            }
        }

        if (_finish || flag > _cStep) {
            _code += tmpCode.substring(0, stepIndex);

            if (flag > _cStep) {
                _cStep = flag;
                wx.postMessage({
                    message: 'next_code'
                });
            }
        }

        if (_finish) {
            console.log('get_finish_code:', JSON.parse(_code));
            console.log('code end time:', new Date().getTime() - _codeStartTime);
            wx.postMessage({
                message: 'finish_code'
            });
        }

        return _finish;
    },

    arr2Color: function (arr, index) {
        let offset = Math.floor(G_W * 0.5),
            start = _pW * 4 * 0,
            pI = (Math.ceil(_gridS * (index - 1) / _pScale) + offset) * 4 + start,
            color = cc.color(arr[pI], arr[pI + 1], arr[pI + 2], arr[pI + 3]);
        // console.log(pI);
        // if (index === 1)
        //     console.log('PI value' + arr[pI] + ',' + arr[pI + 1] + ',' + arr[pI + 2]);
        return cc.colorToHex(color);
    },*/

    getWGShareUrl: function () {
        if (!this.wgUrls || !this.wgUrls.length)
            return DEFAULT_SURL;
        console.log('getWGShareUrl:', this.wgUrls[_sItr] ?
            this.wgUrls[_sItr] :
            this.wgUrls[this.wgUrls.length - 1]);
        return this.wgUrls[_sItr] ?
            this.wgUrls[_sItr] :
            this.wgUrls[this.wgUrls.length - 1];
    },

    getWGShareIcon: function () {
        if (!this.wgIcons || !this.wgIcons.length)
            return DEFAULT_SICON;

        if (++_sItr === this.wgIcons.length)
            _sItr = 0;
        console.log('getWGShareIcon:', this.wgIcons[_sItr]);
        return this.wgIcons[_sItr];
    },

    recommandIndex: function () {
        return _sItr;
    },

    setRecommandData: function (list) {
        let i, len = list.length;

        this.wgUrls = [];
        this.wgIcons = [];

        for (i = 0; i < len; ++i) {
            this.wgUrls[i] = list[i].img;
            this.wgIcons[i] = list[i].icon;
        }
    },

    scaleSharedCanvas: function () {
        if (!require('AppInfo').wx) return;
        if (_scaleOnce) return;

        _scaleOnce = true;

        let openDataContext = wx.getOpenDataContext(),
            sharedCanvas = openDataContext.canvas;

        if (sharedCanvas) {
            sharedCanvas.width = require('UIManager').getRealW() * 0.7;
            sharedCanvas.height = require('UIManager').getRealH() * 0.7;
        }
    },

    // share: function ()
};

module.exports = WGUtil;